package com.example.smartwaterapi.controller;

import com.example.smartwaterapi.common.api.RestApiResponse;
import com.example.smartwaterapi.service.WechatOfficialService;
import com.example.smartwaterapi.service.UserService;
import com.example.smartwaterapi.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号控制器
 */
@Tag(name = "微信公众号", description = "微信公众号相关接口")
@Slf4j
@RestController
@RequestMapping("/api/wechat/official")
public class WechatOfficialController {

    @Autowired
    private WechatOfficialService wechatOfficialService;

    @Autowired
    private UserService userService;

    /**
     * 生成公众号授权URL
     */
    @Operation(summary = "生成公众号授权URL", description = "生成微信公众号网页授权URL")
    @GetMapping("/auth-url")
    public RestApiResponse<String> generateAuthUrl(
            @Parameter(description = "回调地址") @RequestParam(required = false) String redirectUri,
            @Parameter(description = "状态参数") @RequestParam(required = false) String state) {
        
        try {
            String authUrl = wechatOfficialService.generateAuthUrl(redirectUri, state);
            return RestApiResponse.ok("授权URL生成成功", authUrl);
        } catch (Exception e) {
            log.error("生成授权URL失败", e);
            return RestApiResponse.businessError("50001", "生成授权URL失败: " + e.getMessage());
        }
    }

    /**
     * 微信公众号授权回调
     */
    @Operation(summary = "公众号授权回调", description = "处理微信公众号授权回调")
    @GetMapping("/callback")
    public RestApiResponse<Map<String, Object>> callback(
            @Parameter(description = "授权码") @RequestParam String code,
            @Parameter(description = "状态参数") @RequestParam(required = false) String state) {
        
        try {
            log.info("微信公众号授权回调: code={}, state={}", code, state);
            
            Map<String, Object> result = wechatOfficialService.officialLogin(code);
            return RestApiResponse.ok("公众号授权成功", result);
            
        } catch (Exception e) {
            log.error("处理公众号授权回调异常", e);
            return RestApiResponse.businessError("50001", "处理授权回调失败: " + e.getMessage());
        }
    }

    /**
     * 绑定公众号到现有用户
     */
    @Operation(summary = "绑定公众号", description = "将公众号绑定到现有用户账户")
    @PostMapping("/bind")
    public RestApiResponse<String> bindOfficialAccount(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "授权码") @RequestParam String code) {
        
        try {
            boolean success = wechatOfficialService.bindOfficialAccount(userId, code);
            
            if (success) {
                return RestApiResponse.ok("公众号绑定成功");
            } else {
                return RestApiResponse.businessError("50002", "公众号绑定失败");
            }
            
        } catch (Exception e) {
            log.error("绑定公众号异常", e);
            return RestApiResponse.businessError("50002", "绑定公众号失败: " + e.getMessage());
        }
    }

    /**
     * 解绑公众号
     */
    @Operation(summary = "解绑公众号", description = "解绑用户的微信公众号")
    @PostMapping("/unbind")
    public RestApiResponse<String> unbindOfficialAccount(
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        
        try {
            boolean success = wechatOfficialService.unbindOfficialAccount(userId);
            
            if (success) {
                return RestApiResponse.ok("公众号解绑成功");
            } else {
                return RestApiResponse.businessError("50003", "公众号解绑失败");
            }
            
        } catch (Exception e) {
            log.error("解绑公众号异常", e);
            return RestApiResponse.businessError("50003", "解绑公众号失败: " + e.getMessage());
        }
    }

    /**
     * 测试公众号功能
     */
    @Operation(summary = "测试公众号功能", description = "测试微信公众号相关功能")
    @PostMapping("/test")
    public RestApiResponse<Map<String, Object>> testOfficialAccount() {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("timestamp", System.currentTimeMillis());
            result.put("message", "微信公众号功能正常");
            result.put("features", new String[]{
                "公众号授权登录",
                "账号绑定/解绑"
            });
            
            return RestApiResponse.ok("测试成功", result);
        } catch (Exception e) {
            log.error("测试公众号功能异常", e); 
            return RestApiResponse.businessError("50007", "测试失败: " + e.getMessage());
        }
    }
}
